from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from api.models import Book, User
from api.serializers import BookModelSerializerV2, UserModelSerializer, UserModelSerializerV2
from rest_framework import mixins
from rest_framework import generics
from rest_framework import viewsets


# Create your views here.


class BookAPIView(APIView):
    def get(self, request, *args, **kwargs):
        book_id = kwargs.get('id')
        if book_id:
            book = Book.objects.get(pk=book_id, is_delete=False)
            data = BookModelSerializerV2(book).data
            return Response({
                'status': 200,
                'message': '查询单个图书成功',
                'results': data
            })
        else:
            book_objects_all = Book.objects.filter(is_delete=False)
            book_ser = BookModelSerializerV2(book_objects_all, many=True).data

            return Response({
                'status': 200,
                'message': '查询所有图书成功',
                'results': book_ser
            })

    def post(self, request, *args, **kwargs):
        request_data = request.data
        if request_data and isinstance(request_data, dict):
            many = False
        elif request_data and isinstance(request_data, list):
            many = True
        else:
            return Response({
                'status': 400,
                'message': '参数格式有误'
            })
        serializer = BookModelSerializerV2(data=request_data, many=many)
        serializer.is_valid(raise_exception=True)
        book_obj = serializer.save()
        return Response({
            'status': 200,
            'message': '添加图书成功',
            'results': BookModelSerializerV2(book_obj, many=many).data
        })

    def delete(self, request, *args, **kwargs):
        book_id = kwargs.get('id')
        if book_id:
            ids = [book_id]
        else:
            ids = request.data.get('ids')
        response = Book.objects.filter(pk__in=ids, is_delete=False).update(is_delete=True)
        if response:
            return Response({
                'status': 200,
                'message': '删除成功'
            })
        return Response({
            'status': 400,
            'message': '删除失败或图书不存在'
        })

    def put(self, request, *args, **kwargs):
        request_data = request.data
        book_id = kwargs.get('id')

        try:
            book_obj = Book.objects.get(pk=book_id)
        except Book.DoesNotExist:
            return Response({
                'status': 400,
                'message': '图书不存在'
            })

        serializer = BookModelSerializerV2(data=request_data, instance=book_obj)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            'status': 200,
            'message': '修改成功',
            'results': BookModelSerializerV2(book_obj).data
        })

    def patch(self, request, *args, **kwargs):
        request_data = request.data
        book_id = kwargs.get('id')
        # try:
        #     book_obj = Book.objects.get(pk=book_id)
        # except Book.DoesNotExist:
        #     return Response({
        #         'status': 400,
        #         'message': '图书不存在'
        #     })
        # serializer = BookModelSerializerV2(data=request_data, instance=book_obj, partial=True)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # return Response({
        #     'status': 200,
        #     'message': '修改成功',
        #     'results': BookModelSerializerV2(book_obj).data
        # })
        if book_id and isinstance(request_data, dict):
            book_ids = [book_id]
            request_data = [request_data]
        elif not book_id and isinstance(request_data, list):
            book_ids = []
            for dic in request_data:
                pk = dic.pop('id', None)
                if pk:
                    book_ids.append(pk)
                else:
                    return Response({
                        'status': 400,
                        'message': 'PK不存在'
                    })
        else:
            return Response({
                'status': 400,
                'message': '参数格式有误'
            })
        book_list = []
        new_data = []
        for index, pk in enumerate(book_ids):
            try:
                book_obj = Book.objects.get(pk=pk)
                book_list.append(book_obj)
                new_data.append(request_data[index])
            except Book.DoesNotExist:
                continue
        book_ser = BookModelSerializerV2(data=new_data, instance=True, partial=True, many=True)
        book_ser.is_valid(raise_exception=True)
        book_ser.save()
        return Response({
            'status': 200,
            'message': '修改成功'
        })


class BookGenericAPIView(GenericAPIView,
                         mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         mixins.DestroyModelMixin,
                         mixins.CreateModelMixin,
                         mixins.UpdateModelMixin
                         ):
    queryset = Book.objects.all()
    serializer_class = BookModelSerializerV2

    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            return self.retrieve(request, *args, **kwargs)
        return self.list(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.partial_update(request, *args, **kwargs)


class BookGenericAPIViewV3(generics.RetrieveUpdateDestroyAPIView, generics.CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookModelSerializerV2


class UserAPIView(viewsets.GenericViewSet, mixins.ListModelMixin):
    queryset = User.objects.all()
    serializer_class = UserModelSerializer

    def user_login(self, request, *args, **kwargs):
        request_data = request.data
        if request_data in self.list(request, *args, **kwargs).data:
            return Response({
                'status': 200,
                'message': '登陆成功'
            })
        else:
            return Response({
                'status': 400,
                'message': '用户名或密码错误'
            })


class UserAPIViewV2(viewsets.GenericViewSet, mixins.CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = UserModelSerializerV2

    def user_register(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
